<template>
  <div>
    <el-button type="primary" @click="openAddDialog">添加思政评分</el-button>
    <el-table :data="scores" style="margin-top: 10px" border>
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="baseScore" label="基础分" width="100" />
      <el-table-column prop="honorScore" label="荣誉加分" width="100" />
      <el-table-column prop="advisorScore" label="导师加分" width="100" />
      <el-table-column prop="totalScore" label="总分" width="100" />
      <el-table-column prop="deductionDesc" label="处分情况" />
      <el-table-column label="操作" width="160">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" title="思政评分" @close="resetForm">
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="基础分" prop="baseScore">
          <el-input-number v-model="formData.baseScore" :min="0" :max="20" :precision="2" />
        </el-form-item>
        <el-form-item label="荣誉加分" prop="honorScore">
          <el-input-number v-model="formData.honorScore" :min="0" :max="5" :precision="2" />
        </el-form-item>
        <el-form-item label="导师加分" prop="advisorScore">
          <el-input-number v-model="formData.advisorScore" :min="0" :max="5" :precision="2" />
        </el-form-item>
        <el-form-item label="处分情况" prop="deductionDesc">
          <el-input v-model="formData.deductionDesc" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'MoralScoresModule',
  props: {
    studentId: { type: Number, required: true }
  },
  data() {
    return {
      scores: [],
      dialogVisible: false,
      formData: {
        id: null,
        studentId: null,
        baseScore: null,
        honorScore: null,
        advisorScore: null,
        deductionDesc: '',
        totalScore: null
      },
      rules: {
        baseScore: [{ required: true, message: '请输入基础分', trigger: 'blur' }],
        honorScore: [{ required: true, message: '请输入荣誉加分', trigger: 'blur' }],
        advisorScore: [{ required: true, message: '请输入导师加分', trigger: 'blur' }],
        deductionDesc: [{ required: false }]
      }
    }
  },
  watch: {
    studentId: {
      immediate: true,
      handler(newVal) {
        if (typeof newVal === 'number' && !isNaN(newVal)) {
          this.loadData()
        } else {
          this.scores = []
        }
      }
    }
  },
  methods: {
    async loadData() {
      try {
        const res = await axios.get(`/api/moralscores/student/${this.studentId}`)
        this.scores = res.data || []
      } catch (e) {
        this.$message.error('加载思政评分失败')
        this.scores = []
      }
    },
    openAddDialog() {
      this.formData = {
        id: null,
        studentId: this.studentId,
        baseScore: null,
        honorScore: null,
        advisorScore: null,
        deductionDesc: '',
        totalScore: null
      }
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.formData = { ...row, studentId: this.studentId }
      this.dialogVisible = true
    },
    async submit() {
      try {
        const valid = await this.$refs.formRef.validate()
        if (!valid) return

        // 计算总分
        const totalScore = (this.formData.baseScore || 0) + 
                          (this.formData.honorScore || 0) + 
                          (this.formData.advisorScore || 0)
        
        const submitData = {
          ...this.formData,
          totalScore: totalScore
        }

        let res
        if (this.formData.id) {
          res = await axios.put('/api/moralscores', submitData)
        } else {
          res = await axios.post('/api/moralscores', submitData)
        }

        if (res.data && (res.data.code === 200 || res.data > 0)) {
          this.$message.success(this.formData.id ? '更新成功' : '添加成功')
          this.dialogVisible = false
          await this.loadData()
          this.$emit('save-success')
        } else {
          this.$message.error(res.data.message || (this.formData.id ? '更新失败' : '添加失败'))
        }
      } catch (e) {
        this.$message.error('提交失败')
        console.error(e)
      }
    },
    async handleDelete(id) {
      try {
        const res = await axios.delete(`/api/moralscores/${id}`)
        if (res.data && (res.data.code === 200 || res.data > 0)) {
          this.$message.success('删除成功')
          await this.loadData()
          this.$emit('save-success')
        } else {
          this.$message.error('删除失败')
        }
      } catch (e) {
        this.$message.error('删除失败')
      }
    },
    resetForm() {
      this.$refs.formRef?.resetFields()
      this.formData = {
        id: null,
        studentId: this.studentId,
        baseScore: null,
        honorScore: null,
        advisorScore: null,
        deductionDesc: '',
        totalScore: null
      }
    }
  }
}
</script>
